"use strict";
import { OpenAI } from "openai";
import express from "express";
import { createServer } from "http";

const app = express();

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type");
  next();
});

const server = createServer(app);

const openai = new OpenAI({
  baseURL: "https://api.deepseek.com",
  apiKey: "sk-0871f516afa74ee19feece99daee20b6",
});

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.post("/api/chat", async (req, res) => {
  let body = "";
  // 解析请求体
  req.on("data", (chunk) => {
    body += chunk.toString();
  });
  req.on("end", async () => {
    try {
      let messages = JSON.parse(body);
      console.log("收到的消息：", messages);
      // 调用 OpenAI 流式接口
      const completion = await openai.chat.completions.create({
        messages,
        model: "deepseek-chat", // 使用 DeepSeek 模型或其他兼容模型
        stream: true, // 启用流式传输
      });

      // 设置响应头
      res.setHeader("Content-Type", "text/event-stream");
      res.setHeader("Cache-Control", "no-cache");
      res.setHeader("Connection", "keep-alive");
      // 处理流式数据并发送给前端
      for await (const part of completion) {
        const content = part.choices[0]?.delta?.content;
        if (content) {
          res.write(`data: ${JSON.stringify({ content })}\n\n`); // 使用 SSE 格式发送数据
        }
      }

      // 结束流
      res.write("data: [DONE]\n\n");
      res.end();
    } catch (error) {
      console.error("发生错误：", error.message);
      res.status(500).send("服务器内部错误");
    }
  });

});

const PORT = 8002;
server.listen(PORT, () => {
  console.log(`服务器已启动，监听端口 ${PORT}`);
});
